package April.april27;

import jdk.internal.dynalink.beans.StaticClass;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;

/*
利用配置文件，写jdbc的工具类

 */
public class JdbcUtil {
    private static Connection con;
    private static String driverClass;
    private static String url;
    private static String username;
    private static String password;
//    因为工具类会使用户一直调用，而反复的调用这些注册驱动，和建立数据库的连接 会造成资源的浪费，所以写到静态
//    方法块中，或者写到静态方法当中。这样只执行一次。
    static {
        try {
            File file = new File(PropertiesDemo_1.class.getResource("").getFile(), "database.properties").getCanonicalFile();
            FileInputStream in = new FileInputStream(file);
            Properties pro = new Properties();
            pro.load(in);
            driverClass = pro.getProperty("driverClass");
            url = pro.getProperty("url");
            username = pro.getProperty("username");
            password = pro.getProperty("password");
            Class.forName(driverClass);
            con = DriverManager.getConnection(url, username, password);
        }catch(Exception ex){
            throw new RuntimeException("数据库连接失败");
        }
    }

    public static Connection getConnection(){
        return con;
    }
}
